从尾到头打印链表

题目描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:
输入:head = [1,3,2]
输出:[2,3,1]

方法一:栈

如果 Stack 保存 Integer,时间运行为 2ms,应该是多了一步装箱操作的原因

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode cur = head;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
int size = stack.size();
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = stack.pop().val;
}
return res;
}
}

复杂性分析

  • 时间复杂度:O(n)。正向遍历一遍链表,然后从栈弹出全部节点,等于又反向遍历一遍链表。
  • 空间复杂度:O(n)。额外使用一个栈存储链表中的每个节点。

执行结果:通过

  • 执行用时:1 ms, 在所有 Java 提交中击败了74.07%的用户

  • 内存消耗:39.2 MB, 在所有 Java 提交中击败了28.37%的用户

方法二:两次遍历

  1. 第一次遍历得到长度
  2. 第二次遍历,反序给自定义数组赋值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int[] reversePrint(ListNode head) {
ListNode cur = head;
int len = 0;
while(cur != null) {
len++;
cur = cur.next;
}
int[] res = new int[len];

cur = head;
while(cur != null) {
res[len - 1] = cur.val;
len--;
cur = cur.next;
}
return res;
}
}

复杂性分析

  • 时间复杂度:O(n)。遍历两次链表
  • 空间复杂度:O(n)。

执行结果:通过

  • 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

  • 内存消耗:39.1 MB, 在所有 Java 提交中击败了35.24%的用户